package com.hmall.common.interceptor;

import com.hmall.common.utils.UserContext;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListenerAnnotationBeanPostProcessor;
import org.springframework.amqp.rabbit.listener.api.RabbitListenerErrorHandler;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import java.lang.reflect.Method;

/**
 * MQ消息拦截器，用于自动处理用户信息在MQ中的传递
 */
@Configuration
public class MQInterceptor {
    
    /**
     * 消息发送前处理器，自动将当前用户信息添加到消息头中
     * @return MessagePostProcessor
     */
    @Bean
    public MessagePostProcessor userContextPostProcessor() {
        return message -> {
            Long userId = UserContext.getUser();
            if (userId != null) {
                message.getMessageProperties().setHeader("user-info", userId.toString());
            }
            return message;
        };
    }
    
    /**
     * 自定义RabbitListener错误处理器，确保异常时也能清理UserContext
     * @return RabbitListenerErrorHandler
     */
    @Bean
    public RabbitListenerErrorHandler userContextErrorHandler() {
        return (t, m, e) -> {
            try {
                return t;
            } finally {
                // 清理UserContext
                UserContext.removeUser();
            }
        };
    }
}